package com.douyu.ocean.messageSender;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class EmailSender {
	private static Logger log = LoggerFactory.getLogger(EmailSender.class);
	private String host = "";
	private String from = "";
	private String user = "";
	private String passwd = "";
	
	ResourceBundle bundle;
	
	public static void main(String [] args){
		List<String> to = new ArrayList<String>();
		to.add("luopan@douyu.tv");
		EmailSender tmp = new EmailSender();
	    boolean res = tmp.sendEmail("text",to);
	    System.out.println(res);
	}
	   
	public EmailSender(){
		bundle = ResourceBundle.getBundle("monitor");
		host = bundle.getString("email_host");
		user = bundle.getString("email_user");
		passwd = bundle.getString("email_passwd");
		from = bundle.getString("email_from");
	}
	
	public boolean sendEmail(String messageStr, List<String> to){
		boolean isSended = true;
		Properties properties = System.getProperties();
		properties.setProperty("mail.smtp.host", host);
		properties.put("mail.smtp.auth", "true");
		
		
		Session session = Session.getDefaultInstance(properties,new Authenticator(){
			public PasswordAuthentication getPasswordAuthentication(){
				return new PasswordAuthentication(user,passwd);
			}
		});
		
		try{
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(from));
			InternetAddress[] to_address = new InternetAddress[to.size()];
			int i=0;
			for(String email : to){
				to_address[i] = new InternetAddress(email);
				i++;
			}
			
			message.setRecipients(Message.RecipientType.TO, to_address);
			message.setSubject("斗鱼告警");
			message.setText(messageStr);
			Transport.send(message);
			log.warn("sended message by email");
		}catch(SendFailedException e){
			e.printStackTrace();
			log.error("Error when sending email");
			isSended = false;
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return isSended;
	}
}
